#!/bin/bash
#
# Copyright(c) 2012-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#

. $(dirname $3)/conf_framework

check() {
	cur_name=$(basename $2)
	config_file_path=$1
	if compile_module $cur_name "struct block_device bd; bd = *disk_part_iter_next(NULL);" "linux/blk_types.h" "linux/genhd.h"
	then
		echo $cur_name "1" >> $config_file_path
	elif compile_module $cur_name "struct hd_struct hd; hd = *disk_part_iter_next(NULL);" "linux/genhd.h"
    then
		echo $cur_name "2" >> $config_file_path
	else
		echo $cur_name "X" >> $config_file_path
    fi
}

apply() {
    case "$1" in
    "1")
		add_function "
	static inline int cas_bd_get_next_part(struct block_device *bd)
	{
		int part_no = 0;
		struct gendisk *disk = bd->bd_disk;
		struct disk_part_iter piter;
		struct block_device *part;

		mutex_lock(&bd->bd_mutex);

		disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
		while ((part = disk_part_iter_next(&piter))) {
			part_no = part->bd_partno;
			break;
		}
		disk_part_iter_exit(&piter);

		mutex_unlock(&bd->bd_mutex);

		return part_no;
	}" ;;
    "2")
		add_function "
	static inline int cas_bd_get_next_part(struct block_device *bd)
	{
		int part_no = 0;
		struct gendisk *disk = bd->bd_disk;
		struct disk_part_iter piter;
		struct hd_struct *part;

		mutex_lock(&bd->bd_mutex);

		disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
		while ((part = disk_part_iter_next(&piter))) {
			part_no = part->partno;
			break;
		}
		disk_part_iter_exit(&piter);

		mutex_unlock(&bd->bd_mutex);

		return part_no;
	}" ;;
    *)
        exit 1
    esac
}

conf_run $@
